const { app, BrowserWindow, Menu, ipcMain } = require('electron')
const path = require('path')
const { serviceStart, serviceClose, serviceCloseAll } = require('./src/service')
const { routeInit, routeAdd, routeDel, routeDelAll, routes } = require('./src/router')

// BrowserWindow对象
let win;

// 设置窗口
function createWindow() {
  win = new BrowserWindow({
    width: 1000,
    height: 800,
    title: 'mproxy',
    icon: path.join(__dirname, 'www/assets/logo.ico'),
    webPreferences: {
      preload: path.join(__dirname, 'src/preload.js') // 预加载脚本
    }
  })

  win.loadFile('./www/index.html')
  // win.webContents.openDevTools()
}

// 设置菜单
// Menu.setApplicationMenu(Menu.buildFromTemplate([]))

app.disableHardwareAcceleration()
app.whenReady().then(() => {
  handleEvents()
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// 接收渲染进程消息
function handleEvents() {
  // 启动服务
  ipcMain.handle('serviceStart', (event, port) => {
    serviceStart(port, (addr) => handleEventCallback('serviceStartSuccess', addr))
  })

  // 关闭服务
  ipcMain.handle('serviceClose', (event, port) => {
    serviceClose(port)
    handleEventCallback('serviceCloseSuccess', port)
  })

  // 删除服务
  ipcMain.handle('serviceDel', (event, port) => {
    serviceClose(port)
    routeDel(port)
    handleEventCallback('serviceDelSuccess', { port, routes })
  })

  // 删除所有服务
  ipcMain.handle('serviceDelAll', () => {
    serviceCloseAll()
    routeDelAll()
    handleEventCallback('serviceDelAllSuccess', routes)
  })

  // 添加路由
  ipcMain.handle('routeAdd', (event, data) => {
    routeAdd(data.port, data.path, data.url, data.method)
    handleEventCallback('routeAddSuccess', routes)
  })

  // 删除路由
  ipcMain.handle('routeDel', (event, data) => {
    routeDel(data.port, data.path, data.method)
    handleEventCallback('routeDelSuccess', routes)
  })

  // 初始路由表
  ipcMain.handle('routeInit', (event, data) => {
    routeInit(data)
    handleEventCallback('routeInitSuccess', routes)
  })
}

// 发送消息到渲染进程
function handleEventCallback(eventName, data) {
  win.webContents.send(eventName, data)
}